﻿using Microsoft.AspNetCore.Mvc.ViewFeatures;
using My.Core.CustomException;
using My.Core.JobTasks;
using Quartz.Impl.Triggers;
using Quartz.Impl;
using Quartz;
using My.Core.DynamicProxy;
using My.Admin.Helper;
using My.Core.Quartz.Server.IServer;

namespace My.Admin.Tasks.TaskScheduler
{
    /// <summary>
    /// 定时任务http请求
    /// </summary>
    internal class Job_HttpRequest : JobBase, IJob, ISelfScopedAutoInject
	{
		private readonly ISysTasksQzService tasksQzService;
		private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

		public Job_HttpRequest(ISysTasksQzService tasksQzService)
		{
			this.tasksQzService = tasksQzService;
		}
		public async Task Execute(IJobExecutionContext context)
		{
			await ExecuteJob(context, async () => await Run(context));
		}
		public async Task Run(IJobExecutionContext context)
		{
			AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
			var info = await tasksQzService.GetByIdAsync(trigger.JobName);
			if (info == null)
			{
				throw new CustomException($"任务{trigger?.JobName}网络请求执行失败，任务不存在");
			}
			string result;
			if (info.RequestMethod != null && info.RequestMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
			{
				result = await HttpHelper.HttpPostAsync(info.ApiUrl, info.JobParams);
			}
			else
			{
				var url = info.ApiUrl;
				if (url.IndexOf("?") > -1)
				{
					url += "&" + info.JobParams;
				}
				else
				{
					url += "?" + info.JobParams;
				}
				result = await HttpHelper.HttpGetAsync(url);
			}

			logger.Info($"任务【{info.Name}】网络请求执行结果=" + result);
		}
	}
}
